package org.timemachine.listener;

import javax.naming.NamingException;
import javax.persistence.PersistenceException;
import javax.persistence.PostUpdate;
import javax.persistence.PreUpdate;

import org.timemachine.action.facade.EntityChangeFacade;
import org.timemachine.action.facade.ForwardEntityChangeFacade;
import org.timemachine.context.TMScheduleThreadLocal;
import org.timemachine.context.TMThreadLocal;
import org.timemachine.factory.EntityChangeFactory;
import org.timemachine.factory.spi.EntityChange;

public class TimeMachineUpdateListener extends TimeMachineBaseListener {

	@PostUpdate
	public void postUpdate(Object entity) throws Exception{
		try {

			if (!TMScheduleThreadLocal.get().isSchedule() && isEntityHasChangeAnno(entity)) {

				EntityChange entityChange = getEntityChangeForEntity(entity);
				EntityChangeFactory.copyProperties(entityChange, entity);
				entityChange.setChangeType(EntityChangeFactory.CHANGE_TYPE_UPDATE);

				EntityChangeFacade entityChangeFacade = findEntityChangeFacade();
				entityChangeFacade.updateEntityChange(entityChange);
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
		TMScheduleThreadLocal.unset();
	}

	@PreUpdate
	public void preUpdate(Object entity) throws Exception {

		if (TMThreadLocal.getContext().get("forwardDate") != null
				&& !TMScheduleThreadLocal.get().isSchedule()
				&& isEntityHasChangeAnno(entity)) {

			EntityChange entityChange = getEntityChangeForEntity(entity);
			EntityChangeFactory.copyProperties(entityChange, entity);
			entityChange.setChangeType(EntityChangeFactory.CHANGE_TYPE_UPDATE);

			ForwardEntityChangeFacade forwardEntityChangeFacade = findForwardEntityChangeFacade();
			forwardEntityChangeFacade.updateForwardEntityChange(entityChange);
			TMThreadLocal.unset();
			throw new PersistenceException("TimeMachine : save forward entity, exception for normal transaction application entity.");
		}
	}

}
